#!/usr/bin/python
# -*- coding: UTF-8 -*-
#----------------------------------------------------------------------------
# Purpose:
# Copyright Huawei Technologies Co., Ltd. 2010-2018. All rights reserved.
# Author: fanwenyue 00444800
#----------------------------------------------------------------------------

import xml.etree.ElementTree as ET
import hashlib
import argparse
import textwrap
import os


def get_args():
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
                                     description=textwrap.dedent('''
                                     A tool to generate a image ini file'''))
    parser.add_argument('-in_xml', required=True, dest='inFilePath', help='The xml for get image list')
    return parser.parse_args()


def cal_image_hash(filepath):
    sha256_hash = hashlib.sha256()
    with open(filepath, "rb") as f:
        # Read and update hash string value in blocks of 4K
        for byte_block in iter(lambda: f.read(4096), b""):
            sha256_hash.update(byte_block)
    return sha256_hash.hexdigest()


def gen_ini(tree):
    for elem in tree.iter(tag='image'):
        hashVal = cal_image_hash(elem.attrib['path'])
        if hashVal == "":
            return -1
        file_name = os.path.join(elem.attrib['out'], ('{}.ini'.format(elem.attrib['tag'])))
        # print(file_name)
        with open(file_name, 'w+') as f:
            line_elem = [elem.attrib['tag'], hashVal]
            line = '{};\n'.format(',   '.join(line_elem))
            f.write(line)
    return 0


def main():
    args = get_args()
    tree = ET.ElementTree(file=args.inFilePath)
    if tree.getroot().tag != 'image_info':
        print("error in input xml file")
    gen_ini(tree)


if __name__ == '__main__':
    main()
